package com.voc.im.manager;

import com.voc.im.controller.account.Account2Controller;
import io.datafx.controller.flow.Flow;
import io.datafx.controller.flow.FlowException;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.util.HashMap;
import java.util.Map;

public final class StageManager {


    private static double xOffset = 0;
    private static double yOffset = 0;

    private static Map<String, Stage> stringStageMap = new HashMap<>();

    /**
     * 创建舞台
     */
    public static void stage(Class<?> cls) {
        StackPane root = null;
        try {
            root = new Flow(cls).start();
        } catch (FlowException e) {
            e.printStackTrace();
        }
        if (root == null) {
            return;
        }
        Stage stage = stringStageMap.get(cls.getName());
        if (stage == null) {
            stage = new Stage();
            Scene scene = new Scene(root, Color.TRANSPARENT);
            stage.initStyle(StageStyle.TRANSPARENT);
            stage.setScene(scene);

            root.setOnMousePressed(event -> {
                xOffset = event.getSceneX();
                yOffset = event.getSceneY();
            });

            Stage finalStage = stage;
            root.setOnMouseDragged(event -> {
                finalStage.setX(event.getScreenX() - xOffset);
                finalStage.setY(event.getScreenY() - yOffset);
            });

            stringStageMap.put(cls.getName(), stage);
        }
        stage.show();
    }

    /**
     * 关闭指定舞台
     */
    public static void close(Class<?> cls) {
        Stage stage = stringStageMap.get(cls.getName());
        if (stage == null) {
            return;
        }
        stage.close();
        stringStageMap.remove(cls.getName());

        System.out.println("=============");
    }

    /**
     * 删除所有舞台
     */
    public static void closeAll() {
        for (Stage stage : stringStageMap.values()) {
            stage.close();
        }
        stringStageMap.clear();
    }
}
